/**
 * https://leetcode.cn/problems/minimum-index-sum-of-two-lists/
 */
function findRestaurant(list1: string[], list2: string[]): string[] {
  const ans: string[] = [];

  const map = new Map<string, number>();

  // 构建 list2 的映射表
  list2.forEach((item, index) => map.set(item, index));

  let min = Number.MAX_SAFE_INTEGER;
  list1.forEach((item, index) => {
    const index2 = map.get(item);
    if (index2 !== undefined) {
      const total = index + index2;
      if (total <= min) {
        if (total < min) {
          // 小于之前的 min, 先清空数组
          ans.length = 0;
        }
        ans.push(item);
        min = total;
      }
    }
  });

  return ans;
}
